let http = require('http');
let url = require('url');
// console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));
let path = require('path');
let fs = require('fs');

// 解析当前目录:
let workDir = path.resolve('.');
// 组合完整的文件路径:当前目录+'pub'+'index.html':
let filePath = path.join(workDir, 'index.html');

// let server = http.createServer(function(request, response) {
//   // 回调函数接收request和response对象,
//   // 获得HTTP请求的method和url:
//   console.log(request.method + ': ' + request.url);
//   // 将HTTP响应200写入response, 同时设置Content-Type: text/html:
//   response.writeHead(200, { 'Content-Type': 'text/html' });
//   // 将HTTP响应的HTML内容写入response:
//   response.end('<h1>Hello world!</h1>');
// });

// server.listen(8080);

// console.log('Server is running at http://127.0.0.1:8080/');

// 从命令行参数获取rootPath目录，默认是当前目录:
var rootPath = path.resolve(process.argv[2] || '.');

console.log('Static rootPath dir: ' + rootPath);

let server = http.createServer(function(request, response) {
  fs.stat(filePath, function(err, stats) {
    if (!err && stats.isFile()) {
      console.log('200' + request.url);
      response.writeHead(200);
      fs.createReadStream(filePath).pipe(response);
    } else {
      console.log('404' + request.url);
      response.writeHead(404);
      response.end('404 not found');
    }
  });
});

server.listen(8080);
console.log('Server is running at http://127.0.0.1:8080/');
